108. 将有序数组转换为二叉搜索树
108. 将有序数组转换为二叉搜索树
Similar Question
leading to the advanced question
Solution Tips
方案一: 前序遍历思路构造 + 递归
var sortedArrayToBST = function(nums) {
// 递归处理, 从最左侧的节点开始处理, 中间的节点作为根节点
// 优先填满即可
function dfs(low, high) {
if (low > high) {
return null;
}
// 总是选择中间靠左侧的节点
const mid = Math.floor((low + high) / 2);
const root = new TreeNode(nums[mid]);
root.left = dfs(low, mid - 1);
root.right = dfs(mid + 1, high);
return root;
}
return dfs(0, nums.length - 1);
};